package org.sharding.jdbc.spring.boot.autoconfigure;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;

@Configuration
@EnableConfigurationProperties(ShardingMastSlaveProperties.class)
@ConditionalOnProperty({ "sharding.jdbc.data-sources.ds_master.url",
		"sharding.jdbc.master-slave-rule.master-data-source-name" })
public class ShardingDataSourceAutoConfigure {

	private static final Logger logger = LoggerFactory.getLogger(ShardingDataSourceAutoConfigure.class);

	@Autowired
	private ShardingMastSlaveProperties shardingMastSlaveProperties;

	@Bean("masterSlaveDataSource")
	public DataSource masterSlaveDataSource() throws SQLException {
		Map<String, DataSource> dataSourceMap = new HashMap<>();
		dataSourceMap.putAll(shardingMastSlaveProperties.getDataSources());
		DataSource dataSource = MasterSlaveDataSourceFactory.createDataSource(dataSourceMap,
				shardingMastSlaveProperties.getMasterSlaveRule(), new HashMap<>(), new Properties());
		logger.info("masterSlaveDataSource config complete！！!");
		return dataSource;
	}

}
